package org.ycx.upms.web.controller;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.ycx.common.constants.RespCode;
import org.ycx.common.dto.RespMSG;
import org.ycx.upms.common.constants.SecurityConstants;
import org.ycx.upms.dto.SessionUser;
import org.ycx.upms.service.ISecUserService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sec/session")
public class SessionController {

    private static Logger _log = LoggerFactory.getLogger (SecUserController.class);

    private static final String PRE = "sec/session/";

    @Autowired
    private ISecUserService service;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RedisOperationsSessionRepository repository;

    /**
     * 首页
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/index.html")
    public String indexPage(ModelMap modelMap) {
        return PRE + "index";
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/forceLogout/{ids}", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG forceLogout(@PathVariable("ids") String ids) {
        RespMSG msg = new RespMSG (RespCode.SUCCESS);
        repository.delete (ids);
        repository.cleanupExpiredSessions ();
        redisTemplate.delete (SecurityConstants.ONLINE_USER + "-" + ids);
        redisTemplate.opsForList ().remove (SecurityConstants.ONLINE_SESSIONS, -1, ids);
        msg.setData (1);
        return msg;
    }

    @RequestMapping("/list")
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit) {
        List<String> sessions = redisTemplate.opsForList ().range (SecurityConstants.ONLINE_SESSIONS, offset, limit);
        Long size = redisTemplate.opsForList ().size (SecurityConstants.ONLINE_SESSIONS);
        List<SessionUser> sessionUsers = new ArrayList<SessionUser> ();
        for (String session : sessions) {
            String json = redisTemplate.opsForValue ().get (SecurityConstants.ONLINE_USER + "-" + session);
            sessionUsers.add (JSON.parseObject (json, SessionUser.class));
        }
        Map<String, Object> result = new HashMap<> ();
        result.put ("rows", sessionUsers);
        result.put ("total", size);
        return result;
    }
}
